package com.ballyza;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class DownloadFileServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		String toCompile = req.getParameter("value");

		resp.setContentType("text/plain");
		resp.setHeader("Content-Disposition", "attachment;filename=programa.il");
		
		CompileResult result = new CompileResult();
		
		Compiler compiler = new Compiler(result, AnallyzerType.Semantic);
		compiler.compile(toCompile);
		
		String uhu = compiler.getSyntatic().getSemantico().getActions().getCodigo().toString();
		InputStream is = new ByteArrayInputStream(uhu.getBytes("UTF-8"));
		OutputStream os = resp.getOutputStream();
		
		int read = 0;
		while((read = is.read()) != -1) {
			os.write(read);
		}
		
		os.flush();
		os.close();
		
		
		/*
		
		String response = param;
		resp.setContentType("text/plain");  
		resp.setHeader("Content-disposition", "attachment; filename=" + "compilado.txt");   
		resp.getWriter().write(response);*/
		
		//resp.setContentType("text/plain"); 
		//resp.getWriter().write(compiler.getSyntatic().getCodigoGerado().toString());
	}
	
}